package com.le.tester.book.concurrentjavafight.l_11_4;

import org.junit.runner.notification.RunListener;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * createTime：2023/2/4 10:08
 * description：对比AttributeStore,缩小锁的范围
 */
@RunListener.ThreadSafe
public class BetterAttributeStore {

    private final Map<String, String> attributeMap = new HashMap<>();

    public boolean useLocationMatches(String name, String regexp) {
        String key = "users." + name + ".location";
        String location;

        //单锁该行,较少必须串行的代码，存在并发和串行同时进行的场景，那么这个synchronized加锁的位置就可以考虑很多
        synchronized (this) {
            location = attributeMap.get(key);
        }

        if (location == null) {
            return false;
        } else {
            return Pattern.matches(regexp, location);
        }
    }
}
